<template>
  <div class="app-container">
    <el-form ref="form" label-position="top">
      <el-form-item label="数据源：">
        <el-upload
          ref="upload"
          :multiple="false"
          :limit="1"
          :auto-upload="false"
          :on-preview="handlePreview"
          :on-change="handleChange"
          accept=".zip,.rar,.7z"
          class="upload-demo"
          action="string"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">只能上传.zip / .rar / .7z 等压缩格式文件，且不小于1MB，不超过500MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="数据分类：">
        <el-radio v-model="radio" label="movie">影音娱乐</el-radio>
        <el-radio v-model="radio" label="health">健康医疗</el-radio>
        <el-radio v-model="radio" label="news">新闻阅读</el-radio>
        <el-radio v-model="radio" label="other">其它</el-radio>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.native="submitUpload">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { uploadData } from '@/api/table'
export default {
  data() {
    return {
      radio: 'movie',
      reword: 0,
      fileList: []
    }
  },
  methods: {
    submitUpload() {
      if (this.fileList.length === 0) {
        this.$message({
          message: '请选择上传文件',
          type: 'error'
        })
        return false
      }
      this.$confirm(`您本次的上传数据预计奖励${this.reword}个DLB，是否继续？`, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
        center: true
      }).then(() => {
        const formData = new FormData()
        formData.append('file', this.fileList[0].raw)
        formData.append('dataType', this.radio)
        uploadData(formData).then(response => {
          this.$message({
            message: '上传成功！',
            type: 'success'
          })
          this.radio = 'movie'
          this.$refs.upload.clearFiles()
        })
      })
    },
    handleChange(file, fileList) {
      this.fileList = fileList
      this.reword = Math.ceil(file.size / 1024 / 1024)
    },
    handlePreview(file) {
      const isElt500M = file.size / 1024 / 1024 <= 500
      const isEgt1M = file.size / 1024 / 1024 >= 1
      if (!isEgt1M) {
        this.$message.error('上传文件大小不能小于1MB!')
      }
      if (!isElt500M) {
        this.$message.error('上传文件大小不能超过500MB!')
      }
      return isElt500M && isEgt1M
    }
  }
}
</script>
